package com.xinchuang.service.targetSystem;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ObjectUtil;
import com.xinchuang.common.KeyWordSystem;
import com.xinchuang.common.Result;
import com.xinchuang.common.ResultEnum;
import com.xinchuang.common.ResultUtil;
import com.xinchuang.mapper.targetSystem.ZoneMapper;
import com.xinchuang.service.RedisUseService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName IconService
 * @Description: TODO(写一段描述的话)
 * @Author zhangxuan
 * @Date 2021-04-01 16:16
 * @Verion V1.0
 */
@Slf4j
@Service(value = "iconService")
public class IconService {

    @Resource
    private KeyWordSystem keyWordSystem;

    @Resource
    private ZoneMapper zoneMapper;

    @Resource
    private RedisUseService redisUseService;

    public static void main(String[] args) {
        String str = "1.png";
        System.out.println(str.substring(0, str.lastIndexOf(".")));
    }

    public Result<Map<String, Object>> addIcon(MultipartFile file, boolean sign) {
        if (ObjectUtil.isNull(file)) {
            return ResultUtil.error(500, "请选择图片上传");
        }
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf(".") + 1);
        switch (suffixName) {
            case "png":
            case "jpg":
            case "jpeg":
            case "gif":
                break;
            default:
                return ResultUtil.error(ResultEnum.ICON_FORMAT_ERROR);
        }
        if (sign) {
            //变更标记图片名称
            fileName = UUID.randomUUID().toString() + "." + suffixName;
        }
        // 文件存储根路径
        String rootUrl = keyWordSystem.getFILE_URL();
        File rootPath = FileUtil.newFile(rootUrl);
        if (!rootPath.exists()) {
            FileUtil.mkdir(rootPath);
        }
        String middle = null;
        if (sign) {
            middle = "/sign/";
        } else {
            String date = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
            middle = "/icon/" + date + "/";
        }
        return fileUrlPackage(rootUrl, middle, fileName, file);
    }

    public Result<Map<String, Object>> addFile(MultipartFile file) {
        if (ObjectUtil.isNull(file)) {
            return ResultUtil.error(500, "请选择文件上传");
        }
        String fileName = file.getOriginalFilename();
        // 文件存储根路径
        String rootUrl = keyWordSystem.getFILE_URL();
        File rootPath = FileUtil.newFile(rootUrl);
        if (!rootPath.exists()) {
            FileUtil.mkdir(rootPath);
        }
        String date = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
        String middle = "/file/" + date + "/";
        return fileUrlPackage(rootUrl, middle, fileName, file);
    }

    private Result<Map<String, Object>> fileUrlPackage(String rootUrl, String middle, String fileName, MultipartFile file) {
        String iconUrl = middle + fileName;
        try {
            FileUtil.touch(rootUrl + iconUrl);
            FileUtil.writeBytes(file.getBytes(), rootUrl + iconUrl);
        } catch (IOException e) {
            FileUtil.del(rootUrl + iconUrl);
            log.error(e.getMessage(), e);
            return ResultUtil.error(ResultEnum.ICON_UPLOAD_ERROR);
        }
        log.info("上传的文件路径：" + rootUrl + iconUrl + "，文件名为：" + fileName);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("createTime", new SimpleDateFormat("yyyy/MM/dd").format(new Date()));
        resultMap.put("url", middle + fileName);
        resultMap.put("fileUrl", iconUrl);
        resultMap.put("fileName", fileName);
        return ResultUtil.success("上传成功", resultMap);
    }

    public Result getSignList(String typeId) {
        //判断图片是否是选中
        boolean juage = false;
        String bind = "";
        if (StringUtils.isNotBlank(typeId)) {
            String signName = zoneMapper.getSignName(typeId);
            if (StringUtils.isNotBlank(signName)) {
                bind = signName;
                juage = true;
            }
        }
        List<Map<String, Object>> resultList = new ArrayList<>();
        List<String> list = FileUtil.listFileNames(keyWordSystem.getFILE_URL() + "/sign");
        if (CollectionUtil.isNotEmpty(list)) {
            Map<String, Object> map = null;
            for (String s : list) {
                if (s.equals("default.png")) {
                    continue;
                }
                map = new HashMap<>();
                map.put("name", s);
                map.put("url", keyWordSystem.getSERVER_URL() + "/sign/" + s);
                if (juage) {
                    if (bind.equals(s)) {
                        map.put("pitch", true);
                    } else {
                        map.put("pitch", false);
                    }
                } else {
                    map.put("pitch", false);
                }
                resultList.add(map);
            }
        }
        return ResultUtil.success(resultList);
    }

    public Result deleteSign(String name) {
        if (name.equals("default.png")) {
            return ResultUtil.error(500, "系统默认图标，不可删除");
        }
        if (zoneMapper.getSign(name) > 0) {
            return ResultUtil.error(500, "当前图标已被绑定，请解绑后重试");
        }
        File file = FileUtil.newFile(keyWordSystem.getFILE_URL() + "/sign/" + name);
        if (file.isFile()) {
            FileUtil.del(file);
        }
        return ResultUtil.success("删除成功", null);
    }

    /**
     * 添加标记图片
     * @param id
     * @param sign
     * @return
     */
    public Result addSign(String id, String sign) {
        //为空设置为默认图片
        if (StringUtils.isBlank(sign)) {
            sign = "default.png";
        }
        zoneMapper.addSign(id, sign);
        redisUseService.updateTypeSign(id, sign);
        return ResultUtil.success();
    }

}